﻿<div id="app" class="container">
    <!-- 加载提示 -->
    <el-loading v-if="loading" fullscreen text="提交中..."></el-loading>

    <!-- 表单区域 -->
    <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px" style="margin-top: 20px;">
        <!-- 基础信息 -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-row>
            <el-col :span="12">
                <el-form-item label="调拨单号" prop="transnoNo">
                    <el-input v-model="formData.transnoNo" readonly placeholder="自动生成">
                        <el-button slot="append" type="text" v-on:click="generateOrderNo" :disabled="formData.transnoNo">
                            重新生成
                        </el-button>
                    </el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="调拨类型" prop="transferType">
                    <el-select v-model="formData.transferType" placeholder="请选择">
                        <el-option label="货品调拨" value="货品调拨"></el-option>
                        <el-option label="库存预警" value="库存预警"></el-option>
                        <el-option label="满仓调离" value="满仓调离"></el-option>
                        <el-option label="其他调拨" value="其他调拨"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="调拨申请日期" prop="tfrrqdt">
                    <el-date-picker v-model="formData.tfrrqdt"
                                    type="date"
                                    placeholder="选择日期"
                                    value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="调出仓库" prop="outWarehouseId">
                    <el-select v-model="formData.outWarehouseId"
                               placeholder="请选择"
                               filterable
                               clearable
                               v-on:change="handleOutWarehouseChange">
                        <el-option v-for="warehouse in warehouseList"
                                   :key="warehouse.warehouseId"
                                   :label="warehouse.warehouseName"
                                   :value="warehouse.warehouseId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="调入仓库" prop="inWarehouseId">
                    <el-select v-model="formData.inWarehouseId"
                               placeholder="请选择"
                               filterable
                               clearable
                               v-on:change="handleInWarehouseChange">
                        <el-option v-for="warehouse in warehouseList"
                                   :key="warehouse.warehouseId"
                                   :label="warehouse.warehouseName"
                                   :value="warehouse.warehouseId">
                        </el-option>
                    </el-select>
                    <el-alert v-if="isSameWarehouse"
                              title="调入仓库和调出仓库不能为同一仓库"
                              type="error"
                              show-icon
                              :closable="false"
                              style="margin-top: 10px; padding: 5px 15px;">
                    </el-alert>
                </el-form-item>
            </el-col>
            <!-- 调出仓库位（如需显示可保留，否则隐藏） -->
            <el-col :span="12" style="display: none;">
                <el-form-item label="调出仓库位" prop="whloc">
                    <el-select v-model="formData.whloc"
                               placeholder="请选择仓库位"
                               filterable
                               clearable
                               :loading="isLoadingLocation">
                        <el-option v-for="location in warehouseLocationList"
                                   :key="location.locationId"
                                   :label="location.locationName"
                                   :value="location.locationId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <!-- 调入仓库位：隐藏，自动获取 -->
            <el-col :span="12" style="display: none;">
                <el-form-item label="调入仓库位" prop="trwareloc">
                    <el-select v-model="formData.trwareloc"
                               placeholder="自动获取中...">
                        <el-option v-for="location in inWarehouseLocationList"
                                   :key="location.locationId"
                                   :label="location.locationName"
                                   :value="location.locationId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="经办人" prop="handlerId">
                    <el-select v-model="formData.handlerId" placeholder="请选择">
                        <el-option v-for="user in userList"
                                   :key="user.userId"
                                   :label="user.userName"
                                   :value="user.userId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-form-item label="备注" prop="note">
                    <el-input type="textarea" v-model="formData.note" rows="3"></el-input>
                </el-form-item>
            </el-col>
        </el-row>

        <!-- 调拨明细 -->
        <el-divider content-position="left">调拨明细</el-divider>
        <div class="detail-operations" style="margin-bottom: 10px;">
            <el-button type="primary" size="small" v-on:click="openProductDialog">添加货品</el-button>
            <el-button type="danger" size="small" v-on:click="removeDetail" :disabled="selectedDetails.length === 0">移除选中</el-button>
            <el-upload action="/TransferOrder/ImportDetails"
                       :on-success="handleImportSuccess"
                       :before-upload="beforeImport"
                       :on-error="handleImportError"
                       accept=".xlsx,.xls"
                       style="display: inline-block;">
                <el-button type="info" size="small">导入明细</el-button>
            </el-upload>
        </div>
        <el-table :data="detailList"
                  border
                  v-on:selection-change="handleDetailSelection"
                  style="width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号" width="60" fixed="left"></el-table-column>
            <el-table-column prop="product_code" label="货品编号" width="120" fixed="left"></el-table-column>
            <el-table-column prop="product_name" label="货品名称" width="150" fixed="left"></el-table-column>
            <el-table-column prop="specification_model" label="规格型号" width="120"></el-table-column>
            <el-table-column prop="product_type_name" label="货品类型" width="100"></el-table-column>
            <el-table-column prop="out_warehouse_stock" label="调出仓库当前库存" width="140" align="right"></el-table-column>
            <el-table-column prop="in_warehouse_stock" label="调入仓库当前库存" width="140" align="right"></el-table-column>
            <el-table-column prop="transfer_quantity" label="调拨数量" width="120" align="right">
                <template slot-scope="scope">
                    <el-input-number v-model="scope.row.transfer_quantity"
                                     size="mini"
                                     :min="1"
                                     v-on:change="calcAmount(scope.row)"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="in_price" label="入库单价" width="100" align="right">
                <template slot-scope="scope">
                    <el-input-number v-model="scope.row.in_price"
                                     size="mini"
                                     :min="0"
                                     precision="2"
                                     step="0.01"
                                     v-on:change="calcAmount(scope.row)"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="transfer_amount" label="调拨金额" width="120" align="right">
                <template slot-scope="scope">
                    {{ (scope.row.transfer_amount || 0).toFixed(2) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button type="text"
                               size="small"
                               style="color: #ff4d4f;"
                               v-on:click="removeCurrentDetail(scope.row)">
                        移除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 合计信息 -->
        <div style="margin-top: 10px; text-align: right;">
            <el-descriptions column="3" border>
                <el-descriptions-item label="调拨种类">{{ detailList.length }}</el-descriptions-item>
                <el-descriptions-item label="调拨总数量">{{ totalTransferQuantity }}</el-descriptions-item>
                <el-descriptions-item label="调拨总金额">{{ totalTransferAmount.toFixed(2) }}</el-descriptions-item>
            </el-descriptions>
        </div>
    </el-form>

    <!-- 提交按钮区域 -->
    <div style="margin-top: 20px; text-align: right;">
        <el-button v-on:click="goBack">关闭</el-button>
        <el-button type="primary" v-on:click="saveForm(false)">保存</el-button>
    </div>

    <!-- 添加货品弹窗 -->
    <el-dialog title="选择货品"
               :visible.sync="showSelectProductDialog"
               width="900px"
               :close-on-click-modal="false">

        <div class="search-bar" style="margin-bottom: 15px;">
            <el-input v-model="productSearch.keyword"
                      placeholder="输入货品编号/名称搜索"
                      style="width: 300px; margin-right: 10px;"
                      v-on:keyup.enter.native="searchProducts">
            </el-input>
            <el-button type="primary" v-on:click="searchProducts">查询</el-button>
            <el-button v-on:click="resetProductSearch">重置</el-button>
        </div>

        <el-table :data="productList"
                  border
                  v-on:selection-change="handleProductSelection"
                  style="width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column prop="product_code" label="货品编号" width="120"></el-table-column>
            <el-table-column prop="product_name" label="货品名称" width="180"></el-table-column>
            <el-table-column prop="specification_model" label="规格型号" width="150"></el-table-column>
            <el-table-column prop="product_type_name" label="货品类型" width="120"></el-table-column>
            <el-table-column prop="out_warehouse_stock" label="调出仓库存" width="120" align="right"></el-table-column>
            <el-table-column prop="in_warehouse_stock" label="调入仓库存" width="120" align="right"></el-table-column>
            <el-table-column prop="stkInrefp" label="入库单价" width="100" align="right">
                <template slot-scope="scope">{{ (scope.row.stkInrefp || 0).toFixed(2) }}</template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="margin-top: 10px; text-align: right;">
            <el-pagination v-on:size-change="handleProductSizeChange"
                           v-on:current-change="handleProductCurrentChange"
                           :current-page="productPage.pageNum"
                           :page-sizes="[10, 20, 50]"
                           :page-size="productPage.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="productPage.total">
            </el-pagination>
        </div>

        <!-- 弹窗按钮 -->
        <div slot="footer">
            <el-button v-on:click="showSelectProductDialog = false">取消</el-button>
            <el-button type="primary" v-on:click="confirmSelectProducts">确认添加</el-button>
        </div>
    </el-dialog>
</div>

<!-- 引入依赖 -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/element-ui@2.15.13/lib/index.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui@2.15.13/lib/theme-chalk/index.css">

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                loading: false,
                isLoadingLocation: false, // 调出仓库位加载状态
                isLoadingInLocation: false, // 调入仓库位加载状态
                formData: {
                    transnoNo: '',
                    transferType: '',
                    tfrrqdt: '',
                    outWarehouseId: '',
                    inWarehouseId: '',
                    whloc: '', // 调出仓库位
                    trwareloc: '', // 调入仓库位（自动获取，不显示）
                    handlerId: '',
                    note: ''
                },
                warehouseList: [],
                warehouseLocationList: [], // 调出仓库位列表
                inWarehouseLocationList: [], // 调入仓库位列表（用于自动获取）
                userList: [],
                currentUser: '', // 当前登录用户
                formRules: {
                    transnoNo: [{ required: true, message: '请生成调拨单号', trigger: 'blur' }],
                    transferType: [{ required: true, message: '请选择调拨类型', trigger: 'change' }],
                    tfrrqdt: [{ required: true, message: '请选择调拨申请日期', trigger: 'change' }],
                    outWarehouseId: [{ required: true, message: '请选择调出仓库', trigger: 'change' }],
                    inWarehouseId: [{ required: true, message: '请选择调入仓库', trigger: 'change' }],
                    handlerId: [{ required: true, message: '请选择经办人', trigger: 'change' }],
                    trwareloc: [{ required: true, message: '调入仓库位获取失败，请重新选择调入仓库', trigger: 'change' }]
                    // 隐藏的调入仓库位仍需要验证，确保自动获取成功
                },
                detailList: [],
                selectedDetails: [],
                totalTransferQuantity: 0,
                totalTransferAmount: 0,
                isSameWarehouse: false,
                showSelectProductDialog: false,
                productSearch: { keyword: '' },
                productList: [],
                selectedProducts: [],
                productPage: { pageNum: 1, pageSize: 10, total: 0 }
            };
        },
        mounted() {
            console.log('===== 页面初始化开始 =====');
            this.getWarehouses();
            this.getUsers();
            this.generateOrderNo();
            this.setDefaultDate();
            this.getCurrentUser();
            console.log('===== 页面初始化完成 =====');
        },
        methods: {
            // 获取当前登录用户
            getCurrentUser() {
                const _this = this;
                $.get('/User/GetCurrentUser', function(res) {
                    if (res.success && res.data) {
                        _this.currentUser = res.data.userName || 'admin';
                    } else {
                        _this.currentUser = 'admin';
                    }
                }).fail(() => {
                    _this.currentUser = 'admin';
                });
            },

            setDefaultDate() {
                const now = new Date();
                this.formData.tfrrqdt = this.formatDate(now);
            },
            formatDate(date) {
                const y = date.getFullYear();
                const m = (date.getMonth() + 1).toString().padStart(2, '0');
                const d = date.getDate().toString().padStart(2, '0');
                return `${y}-${m}-${d}`;
            },
            getWarehouses() {
                this.loading = true;
                const _this = this;
                $.get('/TransferOrder/GetAllWarehouses', function(res) {
                    _this.loading = false;
                    if (res.success) {
                        _this.warehouseList = res.data || [];
                    } else {
                        _this.$message.error('获取仓库列表失败：' + res.message);
                    }
                }).fail((xhr) => {
                    _this.loading = false;
                    const errorMsg = xhr.responseJSON?.message || '获取仓库列表失败，网络错误';
                    _this.$message.error(errorMsg);
                });
            },
            getUsers() {
                this.loading = true;
                const _this = this;
                $.get('/TransferOrder/GetAllUsers', function(res) {
                    _this.loading = false;
                    if (res.success) {
                        _this.userList = res.data || [];
                    } else {
                        _this.$message.error('获取经办人列表失败：' + res.message);
                    }
                }).fail((xhr) => {
                    _this.loading = false;
                    const errorMsg = xhr.responseJSON?.message || '获取用户列表失败，网络错误';
                    _this.$message.error(errorMsg);
                });
            },
            goBack() {
                window.location.href = '/TransferOrder/Index';
            },
            generateOrderNo() {
                this.loading = true;
                const _this = this;
                $.post('/TransferOrder/GenerateTransferNo', {}, function(res) {
                    _this.loading = false;
                    if (res.success) {
                        _this.formData.transnoNo = res.transferNo;
                    } else {
                        _this.$message.error(res.message || '生成单号失败');
                    }
                }).fail((xhr) => {
                    _this.loading = false;
                    const errorMsg = xhr.responseJSON?.message || '生成单号失败，网络错误';
                    _this.$message.error(errorMsg);
                });
            },
            // 调出仓库变更：加载调出仓库位
            handleOutWarehouseChange() {
                this.formData.whloc = '';
                this.checkWarehouseRelation();

                if (this.formData.outWarehouseId) {
                    this.loadWarehouseLocations(this.formData.outWarehouseId);
                } else {
                    this.warehouseLocationList = [];
                }
            },
            // 调入仓库变更：自动加载调入仓库位并选择第一个
            handleInWarehouseChange() {
                this.formData.trwareloc = ''; // 重置
                this.checkWarehouseRelation();

                if (this.formData.inWarehouseId) {
                    this.loadInWarehouseLocations(this.formData.inWarehouseId);
                } else {
                    this.inWarehouseLocationList = [];
                }
            },
            checkWarehouseRelation() {
                this.isSameWarehouse = this.formData.outWarehouseId &&
                                      this.formData.inWarehouseId &&
                                      this.formData.outWarehouseId === this.formData.inWarehouseId;
            },
            // 加载调出仓库的仓库位
            loadWarehouseLocations(warehouseId) {
                const _this = this;
                this.isLoadingLocation = true;
                $.get(`/TransferOrder/GetLocationsByWarehouse?warehouseId=${warehouseId}`, function(res) {
                    _this.isLoadingLocation = false;
                    if (res.success) {
                        _this.warehouseLocationList = res.data.map(loc => ({
                            locationId: loc.location_id || '',
                            locationName: loc.location_name || ''
                        }));
                        // 自动选择第一个调出仓库位（如果需要）
                        if (_this.warehouseLocationList.length > 0) {
                            _this.formData.whloc = _this.warehouseLocationList[0].locationId;
                        } else {
                            _this.$message.warning('该调出仓库没有可用的仓库位');
                        }
                    } else {
                        _this.$message.error('获取调出仓库位失败：' + res.message);
                        _this.warehouseLocationList = [];
                    }
                }).fail((xhr) => {
                    _this.isLoadingLocation = false;
                    const errorMsg = xhr.responseJSON?.message || '获取调出仓库位失败，网络错误';
                    _this.$message.error(errorMsg);
                    _this.warehouseLocationList = [];
                });
            },
            // 加载调入仓库的仓库位（核心：自动选择第一个）
            loadInWarehouseLocations(warehouseId) {
                const _this = this;
                this.isLoadingInLocation = true;
                console.log('===== 开始自动获取调入仓库位 =====', warehouseId);
                $.get(`/TransferOrder/GetLocationsByWarehouse?warehouseId=${warehouseId}`, function(res) {
                    _this.isLoadingInLocation = false;
                    if (res.success) {
                        _this.inWarehouseLocationList = res.data.map(loc => ({
                            locationId: loc.location_id || '',
                            locationName: loc.location_name || ''
                        }));
                        // 自动选择第一个调入仓库位（关键逻辑）
                        if (_this.inWarehouseLocationList.length > 0) {
                            _this.formData.trwareloc = _this.inWarehouseLocationList[0].locationId;
                            console.log(`自动获取调入仓库位成功：${_this.inWarehouseLocationList[0].locationName}`);
                        } else {
                            _this.$message.error('该调入仓库没有可用的仓库位，请更换仓库');
                            _this.formData.trwareloc = ''; // 清空，触发验证错误
                        }
                    } else {
                        _this.$message.error('获取调入仓库位失败：' + res.message);
                        _this.formData.trwareloc = ''; // 清空，触发验证错误
                        _this.inWarehouseLocationList = [];
                    }
                }).fail((xhr) => {
                    _this.isLoadingInLocation = false;
                    const errorMsg = xhr.responseJSON?.message || '获取调入仓库位失败，网络错误';
                    _this.$message.error(errorMsg);
                    _this.formData.trwareloc = ''; // 清空，触发验证错误
                    _this.inWarehouseLocationList = [];
                });
            },
            openProductDialog() {
                if (!this.formData.outWarehouseId || !this.formData.inWarehouseId) {
                    this.$message.warning('请先选择调出和调入仓库');
                    return;
                }
                // 检查调入仓库位是否已获取
                if (!this.formData.trwareloc) {
                    this.$message.warning('调入仓库位获取中，请稍候重试');
                    return;
                }

                this.selectedProducts = [];
                this.productSearch = { keyword: '' };
                this.productPage.pageNum = 1;
                this.showSelectProductDialog = true;
                this.searchProducts();
            },
            searchProducts() {
                const _this = this;
                const params = {
                    Keyword: this.productSearch.keyword || '',
                    OutWarehouseId: this.formData.outWarehouseId ? Number(this.formData.outWarehouseId) : null,
                    InWarehouseId: this.formData.inWarehouseId ? Number(this.formData.inWarehouseId) : null,
                    PageNum: this.productPage.pageNum,
                    PageSize: this.productPage.pageSize
                };
                $.get('/TransferOrder/SearchProducts', params, function(res) {
                    if (res.success) {
                        // 核心修复1：映射后端返回的 product_type_name 字段，默认显示"未知类型"
                        _this.productList = (res.data.list || []).map(product => ({
                            ...product,
                            specification_model: product.specification_model || '',
                            product_type_name: product.product_type_name || '未知类型', // 确保字段名与后端一致
                            out_warehouse_stock: product.out_warehouse_stock || 0,
                            in_warehouse_stock: product.in_warehouse_stock || 0,
                            stkInrefp: product.stkInrefp || 0
                        }));
                        _this.productPage.total = res.data.total || 0;
                    } else {
                        _this.$message.error('搜索货品失败：' + res.message);
                    }
                }).fail((xhr) => {
                    const errorMsg = xhr.responseJSON?.message || `搜索失败：${xhr.statusText}`;
                    _this.$message.error(errorMsg);
                });
            },
            resetProductSearch() {
                this.productSearch = { keyword: '' };
                this.productPage.pageNum = 1;
                this.searchProducts();
            },
            handleProductSelection(val) {
                this.selectedProducts = val;
            },
            handleProductSizeChange(size) {
                this.productPage.pageSize = size;
                this.productPage.pageNum = 1;
                this.searchProducts();
            },
            handleProductCurrentChange(page) {
                this.productPage.pageNum = page;
                this.searchProducts();
            },
            confirmSelectProducts() {
                if (this.selectedProducts.length === 0) {
                    this.$message.warning('请选择货品');
                    return;
                }
                const existingCodes = this.detailList.map(item => item.product_code);
                const newProducts = this.selectedProducts.filter(p => !existingCodes.includes(p.product_code));
                if (newProducts.length === 0) {
                    this.$message.warning('选中的货品已全部添加');
                    this.showSelectProductDialog = false;
                    return;
                }
                newProducts.forEach(product => {
                    const price = Number(product.stkInrefp) || 0;
                    // 核心修复2：明细列表中存储 product_type_name 字段（与表格列prop一致）
                    this.detailList.push({
                        product_code: product.product_code || '',
                        product_name: product.product_name || '',
                        specification_model: product.specification_model || '',
                        product_type_name: product.product_type_name || '未知类型', // 字段名统一为 product_type_name
                        out_warehouse_stock: Number(product.out_warehouse_stock) || 0,
                        in_warehouse_stock: Number(product.in_warehouse_stock) || 0,
                        transfer_quantity: 1,
                        in_price: price,
                        transfer_amount: price * 1
                    });
                });
                this.calcTotal();
                this.showSelectProductDialog = false;
                this.$message.success(`成功添加 ${newProducts.length} 条货品`);
            },
            removeDetail() {
                const originalLength = this.detailList.length;
                this.detailList = this.detailList.filter(item => !this.selectedDetails.includes(item));
                this.selectedDetails = [];
                this.calcTotal();
                this.$message.success(`移除 ${originalLength - this.detailList.length} 条明细`);
            },
            removeCurrentDetail(row) {
                this.detailList = this.detailList.filter(item => item !== row);
                this.calcTotal();
                this.$message.success('已移除该明细');
            },
            handleDetailSelection(val) {
                this.selectedDetails = val;
            },
            calcAmount(row) {
                const quantity = Number(row.transfer_quantity) || 0;
                const price = Number(row.in_price) || 0;
                row.transfer_amount = quantity * price;
                this.calcTotal();
                this.checkStock(row);
            },
            checkStock(row) {
                const transferQty = Number(row.transfer_quantity) || 0;
                const outStock = Number(row.out_warehouse_stock) || 0;
                if (transferQty > outStock) {
                    this.$message.warning(`【${row.product_name}】调拨数量超过调出仓库当前库存`);
                }
            },
            calcTotal() {
                this.totalTransferQuantity = this.detailList.reduce((sum, item) => sum + (Number(item.transfer_quantity) || 0), 0);
                this.totalTransferAmount = this.detailList.reduce((sum, item) => sum + (Number(item.transfer_amount) || 0), 0);
            },
            beforeImport(file) {
                const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    || file.type === 'application/vnd.ms-excel';
                if (!isExcel) this.$message.error('只能上传Excel文件');
                return isExcel;
            },
            handleImportError(err) {
                this.$message.error('导入失败，网络错误');
            },
            handleImportSuccess(res) {
                if (res.success) {
                    const existingCodes = this.detailList.map(item => item.product_code);
                    const newDetails = res.data
                        .map(item => ({
                            ...item,
                            // 修复3：导入明细时补充 product_type_name 字段
                            product_type_name: item.product_type_name || '未知类型',
                            transfer_quantity: Number(item.transfer_quantity) || 1,
                            in_price: Number(item.in_price) || 0,
                            transfer_amount: (Number(item.transfer_quantity) || 1) * (Number(item.in_price) || 0)
                        }))
                        .filter(item => !existingCodes.includes(item.product_code));

                    this.detailList = [...this.detailList, ...newDetails];
                    this.calcTotal();
                    this.$message.success(`导入成功，新增 ${newDetails.length} 条`);
                } else {
                    this.$message.error(res.message);
                }
            },
            saveForm(isDraft) {
                const _this = this;
                this.$refs.formRef.validate((valid) => {
                    if (!valid) return;
                    if (this.isSameWarehouse) {
                        this.$message.error('调入仓库和调出仓库不能为同一仓库');
                        return;
                    }
                    if (this.detailList.length === 0) {
                        this.$message.warning('请添加调拨明细');
                        return;
                    }
                    if (!this.formData.trwareloc) {
                        this.$message.error('调入仓库位获取失败，请重新选择调入仓库');
                        return;
                    }
                    const overStockItems = this.detailList.filter(item =>
                        (Number(item.transfer_quantity) || 0) > (Number(item.out_warehouse_stock) || 0)
                    );
                    if (overStockItems.length > 0) {
                        this.$confirm(`以下货品调拨数量超过库存：${overStockItems.map(i => i.product_name).join('、')}，是否继续？`, '库存警告', {
                            confirmButtonText: '继续',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            _this.submitForm(isDraft);
                        }).catch(() => {
                            this.$message.info('已取消');
                        });
                        return;
                    }
                    this.submitForm(isDraft);
                });
            },
            submitForm(isDraft) {
                this.loading = true;
                const _this = this;

                const submitData = {
                    transnoNo: this.formData.transnoNo.trim() || '',
                    transferType: this.formData.transferType.trim() || '',
                    tfrrqdt: this.formData.tfrrqdt || '',
                    outWarehouseId: this.formData.outWarehouseId ? Number(this.formData.outWarehouseId) : 0,
                    inWarehouseId: this.formData.inWarehouseId ? Number(this.formData.inWarehouseId) : 0,
                    whloc: String(this.formData.whloc).trim() || '',
                    trwareloc: String(this.formData.trwareloc).trim() || '',
                    handlerId: this.formData.handlerId ? Number(this.formData.handlerId) : 0,
                    note: this.formData.note || '',
                    documentStatus: isDraft ? '0' : '1',
                    outboundStatus: '0',
                    storageStatus: '0',
                    createBy: this.currentUser,
                    createTime: new Date().toISOString(),
                    updateBy: this.currentUser,
                    updateTime: new Date().toISOString(),
                    details: this.detailList.map(item => ({
                        product_code: item.product_code.trim() || '',
                        product_name: item.product_name.trim() || '',
                        specification_model: item.specification_model || '',
                        product_type: item.product_type_name || '', // 提交时后端如需product_type，仍传递该字段
                        transfer_quantity: Number(item.transfer_quantity) || 0,
                        in_price: Number(item.in_price) || 0,
                        transfer_amount: Number(item.transfer_amount) || 0
                    }))
                };

                console.log('===== 提交数据 =====', submitData);

                fetch('/TransferOrder/CreateTransfer', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify(submitData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误状态: ${response.status}`);
                    }
                    return response.json();
                })
                .then(res => {
                    this.loading = false;
                    if (res.success) {
                        this.$message.success(isDraft ? '草稿保存成功' : '创建成功');
                        this.goBack();
                    } else {
                        this.$message.error(res.message || '保存失败');
                    }
                })
                .catch(error => {
                    this.loading = false;
                    this.$message.error(`保存失败: ${error.message}`);
                });
            }
        }
    });
</script>
<style>
    .container {
        padding: 20px;
    }

    .search-bar {
        margin-bottom: 15px;
        padding: 15px;
        background: #f5f7fa;
        border-radius: 4px;
        display: flex;
        align-items: center;
    }

    .detail-operations {
        margin-bottom: 10px;
    }

    .el-table__fixed-left, .el-table__fixed-right {
        height: auto !important;
        bottom: 0 !important;
        box-shadow: 2px 0 6px rgba(0, 0, 0, 0.08);
    }

    @@media (max-width: 768px) {
        .search-bar .el-form-item

    {
        width: 100% !important;
        margin-bottom: 10px;
    }

    }
</style>